const cellHeight = 66.9 + 2;
function shuffle(arrArg) {
    let arr = arrArg.slice();
    for (let i = 0; i < arr.length; i++) {
        let randomIndex = Math.floor(Math.random() * arr.length);
        let temp = arr[randomIndex];
        arr[randomIndex] = arr[i];
        arr[i] = temp;
    }
    return arr;
}
cc.Class({
    extends: cc.Component,

    properties: {
        pfbItemCell: cc.Prefab,
        nodCellParent: cc.Node,
        nodButtons: cc.Node,
        nodBg: cc.Node,
        editBox:cc.EditBox,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    changeEditMode() {
        this.editMode = (this.editMode + 1) % 2;

        if (this.editMode == 0) {
            this.nodBg.color = cc.Color.BLACK;
        } else {
            this.nodBg.color = cc.Color.RED;
        }
    },

    start() {
        this.editMode = 0; // 添加模式
        this.nodCells = [];
        for (let y = 0; y < 9; y++) {
            this.nodCells[y] = [];
            for (let x = 0; x < 11; x++) {
                let node = cc.instantiate(this.pfbItemCell);
                node.parent = this.nodCellParent;
                let pixX = x * cellHeight * Math.cos(30 * Math.PI / 180) - 5 * cellHeight * Math.cos(30 * Math.PI / 180);

                let offsetY = x % 2 == 0 ? cellHeight / 2 : 0;
                let pixY = offsetY + y * cellHeight - 4 * cellHeight;
                node.position = cc.v2(pixX, pixY);

                node.tX = x;
                node.tY = y;

                this.nodCells[y][x] = node;

                node.on('touchstart', () => {
                    if (this.editMode == 0) {
                        node.opacity = 255;
                        node.getChildByName('knotParent').destroyAllChildren();
                    } else {
                        if (!this.firstCell) {
                            this.firstCell = node;
                            node.scale = 0.8;
                            return;
                        }

                        this.firstCell.scale = 1;
                        
                        let pos = cc.v2(node.tX,node.tY);
                        let firstPos = cc.v2(this.firstCell.tX,this.firstCell.tY);

                        this.nodCells[pos.y][pos.x] = this.firstCell;
                        this.nodCells[firstPos.y][firstPos.x] = node;

                        this.firstCell.tX = pos.x;
                        this.firstCell.tY = pos.y;
                        node.tX = firstPos.x;
                        node.tY = firstPos.y;

                        let position = node.position;
                        node.position = this.firstCell.position;
                        this.firstCell.position = position;

                        this.firstCell = null;

                    }
                })
            }
        }

        this._registeEvent();
    },

    _registeEvent() {
        for (let i = 0; i < this.nodButtons.children.length; i++) {
            let node = this.nodButtons.children[i];
            node.on('touchstart', this._onTouchStart, this);
            node.on('touchmove', this._onTouchMove, this);
            node.on('touchend', this._onTouchEnd, this);
            node.on('touchcancel', this._onTouchCancel, this);
            node.name = i + '';
        }

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this._onKeyDown, this);
    },

    _onTouchStart(event) {
        let node = event.target;
        this.curCell = cc.instantiate(node);

        this.curCell.parent = this.nodCellParent;

        let targetPos = this.nodCellParent.convertToNodeSpaceAR(event.getLocation());
        this.curCell.position = targetPos;
    },
    _onTouchMove(event) {
        let targetPos = this.nodCellParent.convertToNodeSpaceAR(event.getLocation());
        this.curCell.position = targetPos;
    },
    _onTouchEnd(event) {
        this.curCell.destroy();
        this.curCell = null;
    },
    _onTouchCancel(event) {
        let gridPos = this._getGridPosByPixPos(this.curCell.position);
        let node = this._getCellNodeByGridPos(gridPos);
        if (!node) {
            this.curCell.destroy();
            this.curCell = null;
            return;
        }
        if (this.curCell.name == '12') {
            node.opacity = 150;
        } else {
            let knot = this.curCell.getChildByName('knot');
            knot.parent = node.getChildByName('knotParent');
        }
        this.curCell.destroy();
        this.curCell = null;
    },

    _onKeyDown(event) {
        switch (event.keyCode) {
            case cc.macro.KEY.space:
                if (!this.curCell || !cc.isValid(this.curCell)) {
                    return;
                }
                this.curCell.getChildByName('knot').angle -= 60;
                break;
        }
    },

    _getGridPosByPixPos(pixPos) {
        let gridX = Math.round(pixPos.x / cellHeight / Math.cos(30 * Math.PI / 180)) + 5;
        let offsetY = gridX % 2 == 0 ? cellHeight / 2 : 0;
        let gridY = Math.round((pixPos.y - offsetY) / cellHeight) + 4;
        return { gridX, gridY };
    },

    _getCellNodeByGridPos(gridPos) {
        let gridX = gridPos.gridX;
        let gridY = gridPos.gridY;

        if (gridX < 0 || gridX > 10 || gridY < 0 || gridY > 8) {
            return;
        }
        return this.nodCells[gridY][gridX];
    },

    randomShuffle() {
        let arr = this._getValidCells();
        let newArr = shuffle(arr);

        for (let i = 0; i < newArr.length; i++) {
            newArr[i].tPositionX = arr[i].x;
            newArr[i].tPositionY = arr[i].y;
            newArr[i].tNewX = arr[i].tX;
            newArr[i].tNewY = arr[i].tY;
        }

        // 交换 nodCells中的位置
        for (let i = 0; i < newArr.length; i++) {
            this.nodCells[arr[i].tY][arr[i].tX] = newArr[i];
        }
        // 交换节点的position
        for (let i = 0; i < newArr.length; i++) {
            newArr[i].x = newArr[i].tPositionX;
            newArr[i].y = newArr[i].tPositionY;
            newArr[i].tX = newArr[i].tNewX;
            newArr[i].tY = newArr[i].tNewY;
        }

    },


    _getValidCells() {
        let arr = [];
        for (let y = 0; y < 9; y++) {
            for (let x = 0; x < 11; x++) {
                let node = this.nodCells[y][x];
                if (node.getChildByName('knotParent').childrenCount <= 0) {
                    continue;
                }

                if (node.opacity == 150) {
                    continue;
                }

                arr.push(node);
            }
        }

        return arr;
    },

    _getFixedCell() {
        for (let y = 0; y < 9; y++) {
            for (let x = 0; x < 11; x++) {
                let node = this.nodCells[y][x];
                if (node.getChildByName('knotParent').childrenCount <= 0) {
                    continue;
                }

                if (node.opacity == 150) {
                    return node;
                }
            }
        }
    },

    saveSuccPos() {
        for (let y = 0; y < 9; y++) {
            for (let x = 0; x < 11; x++) {
                let node = this.nodCells[y][x];
                if (node.getChildByName('knotParent').childrenCount <= 0) {
                    continue;
                }
                
                node.tSuccPos = cc.v2(x, y);
            }
        }
    },

    createJson() {
        let jsonData = {
            'cols': ['id', 'pos', 'isFixed', 'knotData', 'succPos'],
            'vals': [

            ]
        }

        let arr = this._getValidCells();
        let fixedCell = this._getFixedCell();
        if (!fixedCell) {
            console.log('没有固定的格子');
        }else{
            arr.unshift(fixedCell);
        }

        for (let i = 0; i < arr.length; i++) {
            let node = arr[i];
            if(!node.tSuccPos){
                console.log('未记录完成位置')
                return;
            }
            let item = [];
            jsonData['vals'].push(item);

            item[0] = i;
            item[1] = node.tX + '|' + node.tY;
            item[2] = node.opacity == 150 ? 1 : 0;
            item[3] = '';

            let knotParent = node.getChildByName('knotParent');
            for (let j = 0; j < knotParent.children.length; j++) {
                let nodCell = knotParent.children[j];
                let id = this._getKnotId(nodCell.children[0].getComponent(cc.Sprite).spriteFrame.name);
                let angleId = this._getKnotAngle(nodCell.angle);
                let knotId = id + '' + angleId;
                item[3] = item[3] + knotId;

                if(j != knotParent.children.length - 1){
                    item[3] += '|'
                }
            }

            item[4] = node.tSuccPos.x + '|' + node.tSuccPos.y;
        }

        let url = 'knotJson\\' + this.editBox.string + '.json';
        jsb.fileUtils.writeStringToFile(JSON.stringify(jsonData),url);
    },

    _getKnotId(name){
        let id;
        if(name == 'red1'){
            id = 10;
        }else if(name == 'red2'){
            id = 11;
        }else if(name == 'red3'){
            id = 12;
        }else if(name == 'blue1'){
            id = 13;
        }else if(name == 'blue2'){
            id = 14;
        }else if(name == 'blue3'){
            id = 15;
        }else if(name == 'green1'){
            id = 16;
        }else if(name == 'green2'){
            id = 17;
        }else if(name == 'green3'){
            id = 18;
        }else if(name == 'yellow1'){
            id = 19;
        }else if(name == 'yellow2'){
            id = 20;
        }else if(name == 'yellow3'){
            id = 21;
        }
        return id;
    },

    _getKnotAngle(angle){
        let index = angle / -60;
        index = index % 6;
        return index;
    },

    clearAllCell(){
        for (let y = 0; y < 9; y++) {
            for (let x = 0; x < 11; x++) {
                let node = this.nodCells[y][x];
                if (node.getChildByName('knotParent').childrenCount <= 0) {
                    continue;
                }
                
                node.getChildByName('knotParent').destroyAllChildren();
                node.opacity = 255;
            }
        }

        this.editBox.string = '';
    },

    // update (dt) {},
});
